<?php
namespace Admin\Logic;

use Common\Model\LevelModel;

class LevelLogic extends LevelModel
{
	protected function _initialize()
	{
		parent::_initialize();
	}
	
	public function getListByParm($where = array(),$order = 'level_state DESC,level_id ASC')
	{
		$data = $this->where($where)->order($order)->select();
		
		$result = array();
		
		foreach ($data as $key => &$item)
		{
			if( $item['level_pid'] == '0' )
			{
				$result[$item['level_id']] = $item;
			}
			else
			{
				$result[$item['level_pid']]['level'][$item['level_id']] = $item;
			}
		}
		
		return $result;
	}
	
	public function updateLevel($data = array())
	{
		if( empty($data['data']) === false )
		{
			$uri = parse_url($data['data']);
			
			$path = $uri['path'];
			
			$length = strpos($path,'.');
			
			$length = $length === false ? strlen($path) : $length;
			
			$path = substr($path,0,$length);
			
			$data['data'] = $path;
		}
		
		$map = array(
				'order' => 1,
				'default' => 0,
				'state' => 0,
		);
		
		$data = completion($data,$map);
		
		return $this->updateByPK($data);
	}
	
	public function getEdit($options = array())
	{
		return $this->getItem($options);
	}
	
	public function getList()
	{
		$order = 'level_pid ASC,level_order ASC,level_state DESC,level_id ASC';
		
		$data = $this->order($order)->getItems();
		
		$result = array();
		
		foreach ($data as $key => $item)
		{
			$item['state'] = get_format_state($item['level_state']);
			$item['default'] = get_format_state($item['level_default'],array('禁用','启用'));
			$item['edit'] = get_format_url('edit', $item['level_id']);
			$item['delete'] = get_format_url('delete', $item['level_id']);
			
			if( $item['level_pid'] == '0' )
			{
				$result[$item['level_id']] = $item;
			}
			else
			{
				$result[$item['level_pid']]['level'][$item['level_id']] = $item;
			}
		}
		
		return $result;
	}
	
	public function updateByPK($data = array())
	{
		$data = $this->create($data);
		
		return $this->updateRecord($data);
	}
	
	public function deleteByPk($pk = 0)
	{
		if( $this->getByLevelPid($pk) === null )
		{
			return $this->deleteRecord($pk);
		}
		
		$this->error = '请先确认本类下无子分类，如有请先删除。';
		
		return false;
	}
	
}